package myJs.recoverPassword

import myJs.api.Api
import myJs.myPkg.yup.{TestContext, Yup}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.{EmailData, PhoneData, UserNameData}

import scala.collection.mutable
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.JSConverters._

/**
 * Created by yz on 7/12/2022
 */
object Schema {

  case class ValidInfo(v: String, valid: Boolean)

  val cacheMap = mutable.SeqMap[String, ValidInfo]()

  def cacheTest(key: String)(f: String => Future[Boolean]) = (v: String) => {
    val beforeV = cacheMap.getOrElse(key, ValidInfo("", true))
    if (beforeV.v != v) {
      f(v).map { x =>
        cacheMap.put(key, ValidInfo(v, x))
        x
      }.toJSPromise
    } else {
      Future {
        beforeV.valid
      }.toJSPromise
    }
  }

  def nameValidateF(key: String) = cacheTest(key) { v: String =>
    val request = UserNameData(name = v)
    Api.validName(request).map { response =>
      !response.valid
    }
  }

  def captchaValidateF = (v: String, context: TestContext) => {
    val code = context.parent("code")
    code.toLowerCase == v.toLowerCase
  }

  val schema = Yup.`object`().shape(js.Dictionary(
    "name" -> Yup.string().required("用户名或邮箱不能为空！")
      .test(name = "checkExist", message = "该账户不存在！", test = nameValidateF("name")),
    "captcha" -> Yup.string().required("验证码不能为空！")
      .test(name = "checkCaptcha", message = "验证码错误！", test = captchaValidateF),
  ))
}
